package com.cw.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cw.common.api.ResultObject;
import com.cw.dto.OneToManyDto;
import com.cw.dto.RoleGetInfoDto;
import com.cw.entity.SysMenu;
import com.cw.entity.SysRoleMenu;
import com.cw.mapper.SysRoleMenuMapper;
import com.cw.mapper.SysUserRoleMapper;
import com.cw.service.ISysMenuService;
import com.cw.service.ISysRoleMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cw.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 用户角色菜单 服务实现类
 * </p>
 *
 * @author smq
 * @since 2021-04-28
 */
@Service
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements ISysRoleMenuService {
    @Autowired
    private SysRoleMenuMapper sysRoleMenuDao;
    @Autowired
    private SysUserRoleMapper sysUserRoleDao;
    @Autowired
    private ISysMenuService menuService;

    @Override
    public List<SysRoleMenu> getSysRoleMenu(String roleId) {
        return sysRoleMenuDao.getSysRoleMenu(roleId);
    }

    @Override
    public int insertSysRoleMenu(List<SysRoleMenu> list) {
        return sysRoleMenuDao.insertSysRoleMenu(list);
    }

    @Override
    public int updateSysRoleMenu(SysRoleMenu sysRoleMenu) {
        return sysRoleMenuDao.updateSysRoleMenu(sysRoleMenu);
    }

    @Override
    public int deleteSysRoleMenu(String roleId) {
        return sysRoleMenuDao.deleteSysRoleMenu(roleId);
    }

    @Override
    public ResultObject insertRoleMenu(OneToManyDto addDeptAndUserIdDto) {

        String deptId = addDeptAndUserIdDto.getDeptId();
        if (addDeptAndUserIdDto != null && deptId != null) {
            //先删除后添加
            HashMap<String, Object> map = new HashMap<>(5);
            map.put("ROLE_ID", deptId);
            sysRoleMenuDao.deleteByMap(map);
            List<String> userList = addDeptAndUserIdDto.getUserId();
            if (userList != null && userList.size() != 0) {
                userList.forEach(e ->
                        sysRoleMenuDao.insertRoleMenu(UUIDUtil.uuid(), addDeptAndUserIdDto.getDeptId(), e
                        ));
                return ResultObject.successReturn(null);
            }
        } else {
            return ResultObject.failed("部门id不能为空");
        }
        return null;
    }


    @Override
    public ResultObject getIdByRoleId(RoleGetInfoDto roleGetInfoDto) {
        Integer flag = roleGetInfoDto.getFlag();
        String roleId = roleGetInfoDto.getRoleId();
        if (roleGetInfoDto != null && roleGetInfoDto.getFlag() != null) {
            //0用户权限 1权限管理
            switch (flag) {
                case USER_FLAG: {
                    return ResultObject.successReturn(sysUserRoleDao.getUserIdByRoleId(roleId));
                }
                case MENU_FLAG: {
                    return ResultObject.successReturn(sysRoleMenuDao.getMenuIdByRoleId(roleId));
                }
                default: {
                    return ResultObject.failed("标致传输有误");
                }
            }
        } else {
            return ResultObject.failed("没有传输数据");
        }
    }

    /**
     * 根据角色主键查询当前角色拥有哪些菜单以及按钮
     * @param roleId 角色主键
     * @return java.util.List<com.kszs.entity.SysMenu>
     * @author ly
     * @date 2020/10/12 9:30
     */
    @Override
    public List<SysMenu> getRoleAndAuthority(String roleId) {
        return sysRoleMenuDao.getMenuByRoleId(roleId,true);
    }

    /**
     * 根据角色主键查询当前角色拥有哪些菜单以及按钮
     * 与菜单树结合,有权限authority为true
     * @param roleId 角色主键
     * @return java.util.List<com.kszs.entity.SysMenu>
     * @author ly
     * @date 2020/10/12 9:30
     */
    @Override
    public List<SysMenu> getRoleAndAuthorityTree(String roleId) {
//		List<SysMenu> sysMenus = sysRoleMenuDao.getMenuByRoleId(roleId, true);
//		return getChildNodes("0",menuService.getAllSysMenu(),sysMenus);
        return sysRoleMenuDao.getMenuByRoleId(roleId, true);
    }

    /**
     * 通过用户主键获取菜单树
     * @param userId 用户主键
     * @return java.util.List<com.kszs.entity.SysMenu>
     * @author ly
     * @date 2020/9/22 14:17
     */
    @Override
    public List<SysMenu> getSysMenuTreeByUserId(String userId) {

        //获取当前角色对应的菜单
        List<SysMenu> menus = sysRoleMenuDao.getMenuByRoleId(userId, false);
        return sysMenuTree("0", menus);
    }

    /**
     * 获取菜单按钮权限
     * @param roleId  角色主键
     * @param menuIds 菜单主键
     * @return java.util.List<com.kszs.entity.SysRoleMenu>
     * @author ly
     * @date 2020/10/14 11:39
     */
    @Override
    public List<SysRoleMenu> getButton(String roleId, List<String> menuIds) {
        QueryWrapper<SysRoleMenu> wrapper = new QueryWrapper<>();
        wrapper.eq("ROLE_ID", roleId);
        if (!CollectionUtils.isEmpty(menuIds)) {
            wrapper.in("MENU_ID", menuIds);
        }
        return sysRoleMenuDao.selectList(wrapper);
    }

    /**
     * 递归组装成菜单树
     * @param parentId 父级集合
     * @param sysMenus 菜单集合
     * @author ly
     * @date 2020/9/22 14:40
     * @return java.util.List<com.kszs.entity.SysMenu>
     */
    private List<SysMenu> sysMenuTree(String parentId,List<SysMenu> sysMenus) {
        if(CollectionUtils.isEmpty(sysMenus)){
            return null;
        }
        List<SysMenu> childSysMenu=new ArrayList<>();
        for(SysMenu baseDictTree:sysMenus){
            if(baseDictTree.getParentId().equals(parentId)){
                childSysMenu.add(baseDictTree);
            }
        }

        //判断是否有子菜单
        if (childSysMenu.size() == 0) {
            return null;
        }

        for(SysMenu baseDictTree:childSysMenu){
            baseDictTree.setChildNodes(sysMenuTree(baseDictTree.getId(),sysMenus));
        }
        return childSysMenu;
    }

    /**
     * 递归遍历返回菜单树
     * @param id 父级主键
     * @param allBaseDicts 菜单集合
     * @param knownPermissions 已知权限菜单
     * @author ly
     * @date 2020/10/12 15:52
     * @return java.util.List<com.kszs.entity.SysMenu>
     */
    public static List<SysMenu> getChildNodes(String id, List<SysMenu> allBaseDicts, List<SysMenu> knownPermissions) {

        if(CollectionUtils.isEmpty(allBaseDicts)){
            return null;
        }
        List<SysMenu> childBaseDict=new ArrayList<>();
        for(SysMenu baseDictTree:allBaseDicts){
            if(baseDictTree.getParentId().equals(id)){
                childBaseDict.add(baseDictTree);
            }
            Optional<SysMenu> optionalSysMenu = knownPermissions.stream().filter(s-> ObjectUtil.equal(s.getId(),baseDictTree.getId())).findFirst();
            baseDictTree.setAuthority(optionalSysMenu.isPresent());
        }

        //判断是否有子菜单
        if (null == childBaseDict || childBaseDict.size() == 0) {
            return null;
        }

        for(SysMenu baseDictTree:childBaseDict){
            baseDictTree.setChildNodes(getChildNodes(baseDictTree.getId(),allBaseDicts,knownPermissions));
        }
        return childBaseDict;

    }
}
